package com.github.ecbp.common.data.interceptor;

import com.github.ecbp.common.security.config.JwtTokenConfig;
import feign.RequestInterceptor;
import io.seata.core.context.RootContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class FeignInterceptor implements RequestInterceptor {

    @Autowired
    private JwtTokenConfig jwtTokenConfig;

    @Override
    public void apply(feign.RequestTemplate template) {
        String tokenHeader = jwtTokenConfig.getTokenHeader();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Optional.ofNullable(attributes)
                .map(ServletRequestAttributes::getRequest)
                .orElse(null);
        String xid = RootContext.getXID();
        if (null != request) {
            // 把token通过feign传递到被调用的服务
            template.header(tokenHeader, request.getHeader(tokenHeader));
            //分布式事务，全局事务id传递
            if (!StringUtils.isEmpty(xid)){
                template.header(RootContext.KEY_XID, xid);
            }
        }
    }
}